<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\OrderSize as OrderSizeService;
use think\Db;

/**
 * 委外管理
 */
class OrderOutgo extends Base
{
    /**
     * 切片打包外发打标--数据生成
     * @param $orderId
     * @param $cut_packages
     * @param $cut_packages_remark
     * @date 2021/11/24
     * @return array
     * @author zhuguosen 905502314@qq.com
     */
    public function cutPackageLabel($orderId, $cut_packages, $cut_packages_remark)
    {
        //1 没发货就可以重新生成码，如有修改就不能修改了。
        $order_outgo_cpl_info = db("order_outgo_cpl")->where([['order_id', '=', $orderId], ['status_send', '=', 1]])->find();
        if (isset($order_outgo_cpl_info['id'])) {
            return ['code' => 11, 'msg' => '失败'];
        }
        $order_outgo_info = db("order_outgo")->where([['order_id', '=', $orderId]])->find();
        if (intval($order_outgo_info['group_id']) <= 0) {
            return ['code' => 12, 'msg' => '失败'];
        }
        // 启动事务
        Db::startTrans();
        try {
            $temp = db("order_outgo")->where([['order_id', '=', $orderId], ['group_id', '>', 0]])->update(['cut_packages' => $cut_packages, 'cut_packages_remark' => $cut_packages_remark]);
            if (!is_int($temp) || $temp > 1) {
                Db::rollback();
                return ['code' => 12, 'msg' => '失败'];
            }
            db("order_outgo_cpl")->where([['order_id', '=', $orderId], ['status_send', '=', 0]])->delete();
            $insertData = [];
            for ($i = 1; $i <= $cut_packages; $i++) {
                $insertData[] = [
                    'order_id' => $orderId,
                    'num_0' => $i,
                    'num_1' => $cut_packages,
                    'status' => 0,
                    'status_send' => 0,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
            }
            $temp3 = db("order_outgo_cpl")->insertAll($insertData);
            if ($temp3 != $cut_packages) {
                Db::rollback();
                return ['code' => 13, 'msg' => '失败'];
            }
            Db::commit();
            return ['code' => 1, 'msg' => '成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 14, 'msg' => '失败'];
        }
        return ['code' => 1, 'msg' => '成功'];
    }

    public function setFactoryOutgoIdV2_add($orderId, $factoryOutgoId)
    {
        //1,如发货了，不能修改工厂名
        //2,
        $res = db('order_outgo')->insert([
            'order_id' => $orderId,
            'group_id' => $factoryOutgoId,
            'hope_shipment_time' => 0,
            'cut_packages' => 0,
            'cut_packages_remark' => '',
            'create_time' => time(),
            'update_time' => time(),
        ]);
        //默认生成一个切片打包外发打标--数据生成
        $this->cutPackageLabel($orderId, 1, '裁片');
        return $res;
    }

    public function setFactoryOutgoIdV2_edit($orderId, $factoryOutgoId)
    {
        //1,如发货了，不能修改工厂名
        //2,
        $ret = db('order_outgo')->where('order_id', $orderId)->update([
            'group_id' => $factoryOutgoId,
            'update_time' => time(),
        ]);
        return $ret;
    }

    /**
     * 外发管理》节点进度》待发货  确认发货
     * @param $order_ids
     * @date 2021/12/8
     * @return bool
     * @author zhuguosen 905502314@qq.com
     */
    public function sendConfirm($order_ids)
    {
        $list = db('order_outgo oot')
            ->field('cpl.order_id,min(cpl.status_send) min_status_send')
            ->join('wx_order_outgo_cpl cpl ', 'oot.order_id=cpl.order_id', 'left')
            ->where([
                ['oot.order_id', 'in', $order_ids],
                ['cpl.status', '=', 0],
            ])
            ->group('cpl.order_id')
            ->select();
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                if ($v['min_status_send'] == 1) {
                    db('order_outgo oot')->where([
                        ['oot.order_id', 'in', $order_ids],
                    ])->update([
                        'status' => 200,
                        'admin_id' => ADMIN_ID,
                        'admin_id_send_0' => ADMIN_ID,
                        'time_send_0' => time(),
                        'update_time' => time(),
                    ]);
                }
            }
        }
        return true;
    }

    public function waitDeliver_data_init($orderId, $factoryOutgoId)
    {
        $res = db('order_outgo')->insert([
            'order_id' => $orderId,
            'group_id' => $factoryOutgoId,
            'hope_shipment_time' => 0,
            'cut_packages' => 0,
            'cut_packages_remark' => '',
            'create_time' => time(),
            'update_time' => time(),
        ]);
        return $res;
    }

    /**
     * 尾部完成时 同步 外发厂的信息状态
     * wx_order_outgo 的status说明
     * 发货：0没发货 1发部分  对应 wx_order_outgo_cpl中的发货状态
     * 车缝中  200 2全部发货  201 确认回货
     * 后整中 300 对应上级201确认回货   301 已退货  302 外协尾部
     * 完成1000 对应旧系统逻辑
     * @date 2021/12/3
     * @author zhuguosen 905502314@qq.com
     */
    public function tail_done($orderId)
    {
        $temp = db('order o')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->where([
                ['ft.type', '=', 1],
                ['oot.order_id', '=', $orderId],
                ['oot.group_id', '>', 0],
                ['oot.status', '=', 300],
            ])->update([
                'oot.status' => 1000,
                'oot.batch_status' => 1,
            ]);
        if ($temp != 1) {
            return ['code' => 10, 'msg' => '失败'];
        }
        return ['code' => 1, 'msg' => '成功'];
    }

    /**
     * 检查尾部完成时 委外管理的卡点
     * @param $orderId
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/13
     */
    public function tail_done_check($orderId)
    {
        $temp = db('order o')
            ->field('oot.status,oot.batch_status,oot.batch_num')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->where([
                ['ft.type', '=', 1],
                ['oot.order_id', '=', $orderId],
                ['oot.group_id', '>', 0],
//                ['oot.status', '=', 300],
            ])->find();
        if (isset($temp['status']) && ($temp['status'] > 300 || $temp['status'] < 300)) {
            $msg = '此订单不在节点进度的后整中，无法完成';
            $temp['status'] == 301 && $msg = "此订单还是节点进度的已退货，请选设置回后整中";
            $temp['status'] == 302 && $msg = "此订单还是节点进度的外协尾部，请选设置回后整中";
            return ['code' => $temp['status'], 'msg' => $msg];
        }
        //添加卡点，如在分批回货的不能完成
        if ($temp['status'] == 300 && $temp['batch_status'] == 0) {
            return ['code' => 10, 'msg' => "此订单在节点进度的后整中，没有全部回货"];
        }
        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 订单外发-动作记录
     * wx_order_outgo_action_log表修改
     * @date 2021/12/8
     * @author zhuguosen 905502314@qq.com
     */
    public function action_log($param)
    {
        switch ($param['type']) {
            case 'dispatching_unitSet':
                $info = db('order o')
                    ->field('oot.status,oot.order_id ,o.client_ordernum')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->where([
                        ['o.id', '=', $param['param']['order_id']],
                    ])
                    ->find();
                $temp3 = db("order_outgo_action_log")->insert([
                    'order_id' => $info['order_id'],
                    'client_ordernum' => $info['client_ordernum'],
                    'type' => $param['type'],
                    'status' => $info['status'],
                    'u_out_type' => $param['param']['u_out_type'],
                    'u_scale' => $param['param']['u_scale'],
                    'u_price_manual' => $param['param']['u_price_manual'],
                    'u_scale_changkuan' => $param['param']['u_scale_changkuan'],
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
            case 'sewing_confirmReturnGoods':
            case 'sewing_confirmReturnGoods_finish':
            case 'sewing_confirmReturnGoods_batch':
                $info = db('order_outgo oot')
                    ->field('oot.status')
                    ->where([
                        ['oot.order_id', '=', $param['param']['order_id']],
                    ])
                    ->find();
                $temp3 = db("order_outgo_action_log")->insert([
                    'order_id' => $param['param']['order_id'],
                    'client_ordernum' => $param['param']['client_ordernum'],
                    'type' => $param['type'],
                    'status' => $info['status'],
                    'return_goods_num' => serialize($param['param']['return_goods_num']),
                    'owe' => serialize($param['param']['owe']),
                    'sew_return_material_flag' => $param['param']['sew_return_material_flag'],
                    'batch_status' => $param['param']['batch_status'] ?? 1,
                    'batch_num' => $param['param']['batch_num'] ?? 0,
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
            case 'waitDeliver_sendConfirm':
                $res_param = [];
                foreach ($param['param'] as $k => $v) {
                    $res_param[$v[0]][] = $v;
                }
                foreach ($res_param as $k => $v) {
                    $info = db('order_outgo oot')
                        ->field('oot.status')
                        ->where([
                            ['oot.order_id', '=', $v[0][0]],
                        ])
                        ->find();
                    $temp3 = db("order_outgo_action_log")->insert([
                        'order_id' => $v[0][0],
                        'client_ordernum' => $v[0][1],
                        'type' => $param['type'],
                        'status' => $info['status'],
                        'send_goods_data' => serialize($v),
                        'admin_id' => ADMIN_ID,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);
                }
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
            case 'afterFinishing_outTail':
                foreach ($param['param']['order_ids'] as $k => $v) {
                    $info = db('order o')
                        ->field('o.id as order_id ,o.client_ordernum
                        ,oot.*')
                        ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                        ->where([
                            ['o.client_ordernum', '=', $v],
                        ])
                        ->find();
                    $temp3 = db("order_outgo_action_log")->insert([
                        'order_id' => $info['order_id'],
                        'client_ordernum' => $info['client_ordernum'],
                        'type' => $param['type'],
                        'status' => $info['status'],
                        'after_out_type' => $info['after_out_type'],
                        'after_factory_id' => $info['after_factory_id'],
                        'after_group_id' => $info['after_group_id'],
                        'after_price' => $info['after_price'],
                        'after_num' => $info['after_num'],
                        'admin_id' => ADMIN_ID,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);
                    if ($temp3 != 1) {
                        return false;
                    }
                }
                return true;
                break;
            case 'outgoTail_confirmReturnGoods':
                $info = db('order_outgo oot')
                    ->field('oot.status')
                    ->where([
                        ['oot.order_id', '=', $param['param']['order_id']],
                    ])
                    ->find();
                $temp3 = db("order_outgo_action_log")->insert([
                    'order_id' => $param['param']['order_id'],
                    'client_ordernum' => $param['param']['client_ordernum'],
                    'type' => $param['type'],
                    'status' => $info['status'],
                    'return_goods_num' => $param['param']['sew_return_goods_num'],
                    'owe' => $param['param']['sew_owe'],
                    'sew_return_material_flag' => $param['param']['sew_return_material_flag'],
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
            case 'afterFinishing_returnTime':
                $info = db('order o')
                    ->field('oot.status,oot.order_id ,o.client_ordernum')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->where([
                        ['o.id', '=', $param['param']['order_id']],
                    ])
                    ->find();
                $temp3 = db("order_outgo_action_log")->insert([
                    'order_id' => $info['order_id'],
                    'client_ordernum' => $info['client_ordernum'],
                    'type' => $param['type'],
                    'status' => $info['status'],
                    'after_return_reason' => $param['param']['after_return_reason'],
                    'after_return_num' => $param['param']['after_return_num'],
                    'after_return_time' => $param['param']['after_return_time'],
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
            case 'afterFinishing_returnGoods':
                foreach ($param['param'] as $k => $v) {
                    $info = db('order o')
                        ->field('oot.status,oot.order_id ,o.client_ordernum')
                        ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                        ->where([
                            ['o.id', '=', $v['order_id']],
                        ])
                        ->find();
                    $temp3 = db("order_outgo_action_log")->insert([
                        'order_id' => $info['order_id'],
                        'client_ordernum' => $info['client_ordernum'],
                        'type' => $param['type'],
                        'status' => $info['status'],
                        'after_refund_reason' => $v['after_refund_reason'],
                        'after_refund_type' => $v['after_refund_type'],
                        'after_refund_num' => $v['after_refund_num'],
                        'admin_id' => ADMIN_ID,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);
                    if ($temp3 != 1) {
                        return false;
                    }
                }
                return true;
                break;
            case 'finishReturn_confirmReturnGoods':
                $info = db('order_outgo oot')
                    ->field('oot.status')
                    ->where([
                        ['oot.order_id', '=', $param['param']['order_id']],
                    ])
                    ->find();
                $temp3 = db("order_outgo_action_log")->insert([
                    'order_id' => $param['param']['order_id'],
                    'client_ordernum' => $param['param']['client_ordernum'],
                    'type' => $param['type'],
                    'status' => $info['status'],
                    'return_goods_num' => $param['param']['sew_return_goods_num'],
                    'owe' => $param['param']['sew_owe'],
                    'sew_return_material_flag' => $param['param']['sew_return_material_flag'],
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                if ($temp3 != 1) {
                    return false;
                }
                return true;
                break;
        }
    }

    /**
     * 委外对帐--在业务没完成前的数据添加与修改
     * @date 2021/12/22
     * @author zhuguosen 905502314@qq.com
     */
    public function order_status_0($param)
    {
        switch ($param['type']) {
            case 'waitDeliver_sendConfirm':
                return $this->_order_status_0_waitDeliver_sendConfirm($param['param']);
                break;
            case 'sewing_confirmReturnGoods':
            case 'sewing_confirmReturnGoods_v2':
                return $this->_order_status_0_sewing_confirmReturnGoods($param['param']);
                break;
            case 'afterFinishing_outTail':
                return $this->_order_status_0_afterFinishing_outTail($param['param']);
                break;
            case 'outgoTail_confirmReturnGoods':
                return $this->_order_status_0_outgoTail_confirmReturnGoods($param['param']);
                break;
            case 'afterFinishing_returnTime'://返工计时设置，同步财务的 委外类型的车间  的 ，“返工工时 返工金额 返工数量 计时工价(元/时) ”。 返工金额=返工工时*计时工价(元/时)
                return $this->_order_status_0_afterFinishing_returnTime($param['param']);
                break;
        }
    }

    private function _order_status_0_waitDeliver_sendConfirm($param)
    {
        //1,查询信息
        $list = db('order_outgo oot')
            ->field('oot.status,oot.order_id')
            ->where([
                ['oot.order_id', 'in', $param['order_ids']],
                ['oot.status', '=', 200],
            ])
            ->select();
        if (count($list) == 0) {
            return true;
        }
        foreach ($list as $k => $v) {
            $where = [
                ['o.id', '=', $v['order_id']],
            ];
            $info = db('order o')
                ->field('o.id as order_id ,o.client_ordernum,o.sku ,o.is_auto_import,o.order_price
                ,oe.cost_little
                ,oe.cost_jiagong_littleSumCost,oe.cost_jiagong_scale
                ,oe.cost_jiagong_sumCostForSale,oe.dress_changkuan_unitPrice
                ,o.factory_id,oot.group_id ,sum(om.shicai_count) sum_shicai_count
                ,g.unit_cutting,g.unit_workshop,g.unit_tail,g.unti_manual,g.unit_time_price,g.unit_set_flag
                ,oot.u_out_type,oot.u_scale,oot.u_price_manual,oot.u_scale_changkuan
                ')
                ->join('order_ext oe', "o.id=oe.order_id", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('group g', "g.id=oot.group_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_material om ', 'om.order_id=o.id', 'left')
                ->where($where)->group('om.order_id')->find();
            if ($info['unit_set_flag'] == 0) {
                if ($info['u_out_type'] == '') {
                    return false;
                }
                if ($info['u_scale'] <= 0 && $info['u_price_manual'] <= 0) {
                    return false;
                }
            }
            $info2 = db('order_outgo_order')->where([
                ['order_id', '=', $info['order_id']],
                ['type', '=', 'waitDeliver_sendConfirm'],
            ])->find();
            if (isset($info2['id'])) {
                return false;
            }
            //2,计算处理
            //3,添加或修改 wx_order_outgo_order表
            $temp = db('order_outgo_order')->insert([
                'order_id' => $info['order_id'],
                'client_ordernum' => $info['client_ordernum'],
                'type' => 'waitDeliver_sendConfirm',
                'status' => $v['status'],
                'factory_id' => $info['factory_id'],
                'factory_child_id' => $info['group_id'],
                'sum_shicai_count' => $info['sum_shicai_count'],
                'group_out_type' => $info['unit_set_flag'] == 2 ? 2 : $info['u_out_type'],//2车  unit_set_flag=0就以u_out_type为主
                'group_unit_price' => $info['unit_workshop'],
                'order_price' => $info['order_price'],
                'cost_little' => $info['cost_little'],
                'cost_jiagong_littleSumCost' => $info['cost_jiagong_littleSumCost'],
                'cost_jiagong_scale' => $info['cost_jiagong_scale'],
                'cost_jiagong_sumCostForSale' => $info['cost_jiagong_sumCostForSale'],
                'dress_changkuan_unitPrice' => $info['dress_changkuan_unitPrice'],
                'caichuang_t_strip_price' => 0,
                'confiscation_num' => 0,
                'after_return_time' => 0,
                'unit_time_price' => 0,
                'other_cut_payment' => 0,
                'u_out_type' => $info['u_out_type'],
                'u_scale' => $info['u_scale'],
                'u_price_manual' => $info['u_price_manual'],
                'u_scale_changkuan' => $info['u_scale_changkuan'],
                'unit_set_flag' => $info['unit_set_flag'],
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            if ($temp != 1) {
                return false;
            }
        }
        return true;
    }

    private function _order_status_0_sewing_confirmReturnGoods($param)
    {
        //1,查询信息
        $info = db('order o')
            ->field('oot.order_id ,oot.sew_return_goods_num , oot.sew_owe , oot.sew_return_material_flag')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->where([
                ['oot.order_id', '=', $param['order_id']],
            ])
            ->find();
        //2,计算处理
        //3,添加或修改 wx_order_outgo_order表
        $temp = db('order_outgo_order')->where([
            'order_id' => $param['order_id'],
            'type' => 'waitDeliver_sendConfirm',
        ])->update([
            'status' => 1101,
            'sum_che_return_goods_num' => $info['sew_return_goods_num'],
            'sum_che_owe' => $info['sew_owe'],
            'sum_che_return_material_flag' => $info['sew_return_material_flag'],
            'admin_id' => ADMIN_ID,
            'update_time' => time(),
        ]);
        if ($temp != 1) {
            return false;
        }
        return true;
    }

    private function _order_status_0_afterFinishing_outTail($param)
    {
        //1,查询信息
        $list = db('order o')
            ->field('oot.status,oot.order_id,oot.data_status')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->where([
                ['o.client_ordernum', 'in', $param['order_ids']],
                ['oot.status', '=', 302],
            ])
            ->select();
        if (count($list) == 0) {
            return false;
        }
        foreach ($list as $k => $v) {
            if ($v['data_status'] > 0) {//1号以上数据，不流入财务
                continue;
            }
            $where = [
                ['o.id', '=', $v['order_id']],
            ];
            $info = db('order o')
                ->field('o.id as order_id ,o.client_ordernum,o.sku ,o.is_auto_import,o.order_price
                ,oext.cost_little
                ,o.factory_id,oot.group_id ,sum(om.shicai_count) sum_shicai_count
                ,g.unit_cutting,g.unit_workshop,g.unit_tail,g.unti_manual,g.unit_time_price
                ,oot.after_factory_id  ,oot.after_group_id ,oot.after_out_type
                ')
                ->join('order_ext oext', "o.id=oext.order_id", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('group g', "g.id=oot.group_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_material om ', 'om.order_id=o.id', 'left')
                ->where($where)->group('om.order_id')->find();
            //2,计算处理
            //3,添加或修改 wx_order_outgo_order表
            $temp = db('order_outgo_order')->insert([
                'order_id' => $info['order_id'],
                'client_ordernum' => $info['client_ordernum'],
                'type' => 'afterFinishing_outTail',
                'status' => 302,
                'factory_id' => $info['after_factory_id'],
                'factory_child_id' => $info['after_group_id'],
                'sum_shicai_count' => $info['sum_shicai_count'],
                'group_out_type' => $info['after_out_type'],//2车
                'group_unit_price' => $info['unit_tail'] > 0 ? $info['unit_tail'] : $info['unti_manual'],
                'order_price' => $info['order_price'],
                'cost_little' => $info['cost_little'],
                'caichuang_t_strip_price' => 0,
                'confiscation_num' => 0,
                'after_return_time' => 0,
                'unit_time_price' => 0,
                'other_cut_payment' => 0,
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            if ($temp != 1) {
                return false;
            }
        }
        return true;
    }

    private function _order_status_0_outgoTail_confirmReturnGoods($param)
    {
        //1,查询信息
        $info = db('order o')
            ->field('oot.status,oot.order_id ,oot.after_factory_id , oot.after_group_id,oot.data_status')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->where([
                ['o.id', '=', $param['order_id']],
                ['oot.status', '=', 300],
            ])
            ->find();
        if ($info['data_status'] > 0) {
            return true;
        }
        //2,计算处理
        //3,添加或修改 wx_order_outgo_order表
        $temp = db('order_outgo_order')->where([
            'order_id' => $param['order_id'],
            'factory_id' => $info['after_factory_id'],
            'factory_child_id' => $info['after_group_id'],
            'type' => 'afterFinishing_outTail',
        ])->update([
            'status' => 1101,
            'sum_wei_return_goods_num' => $param['sew_return_goods_num'],
            'sum_wei_owe' => $param['sew_owe'],
            'sum_wei_return_material_flag' => $param['sew_return_material_flag'],
            'admin_id' => ADMIN_ID,
            'update_time' => time(),
        ]);
        if ($temp != 1) {
            return false;
        }
        return true;
    }

    private function _order_status_0_afterFinishing_returnTime($param)
    {
        //1,查询信息
        $info = db('order o')
            ->field('o.id,o.client_ordernum 
                ,g.unit_time_price
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where([
                ['o.id', '=', $param['order_id']],
            ])->find();
        $info2 = db('order_outgo_order')
            ->field('id')
            ->where([
                ['order_id', '=', $param['order_id']],
                ['status', '<', 1120],
                ['group_out_type', '=', 2],
            ])
            ->find();
        if (!isset($info2['id']) || $info['unit_time_price'] <= 0) {
            return false;
        }
        //2,计算处理
        //3,添加或修改 wx_order_outgo_order表
        $temp = db('order_outgo_order')->where([
            ['order_id', '=', $param['order_id']],
            ['status', '<', 1120],
            ['group_out_type', '=', 2],
        ])->update([
            'after_return_num' => $param['after_return_num'],
            'after_return_time' => $param['after_return_time'],
            'after_return_price' => sprintf("%.2f", $param['after_return_time'] * $info['unit_time_price']),
            'unit_time_price' => $info['unit_time_price'],
            'admin_id' => ADMIN_ID,
            'update_time' => time(),
        ]);
        if ($temp != 1) {
            return false;
        }
        return true;
    }

    /**
     * 委外对帐与结算--业务完成后，对帐流程总管理
     * wx_order_outgo_order 表的 status 说明：0-1100以下为业务进度状态  1101，完成后开始对帐审核 1102驳回的帐单  1120，已审核 1130，复核 1140，已提交并结算 1200，已付款即结束不可修改了
     * @date 2021/12/6
     * @author zhuguosen 905502314@qq.com
     */
    public function order_check_manager()
    {
    }

    /**
     * wx_order_outgo 标识 数据整体类型 0完全数据 1 1号数据型
     * 修改工厂id--应用1号数据型
     * 解决问题点：订单已在完成车间，尾部还没完成的订单时，修改不了工厂id的问题。
     * 1号数据型--条件：
     * 1，财务审核过的不能修改。---不用判断
     * 2，尾部完成的订单不修改。
     * 修改方案：
     * 1，添加--数据一直到后整中，并标识为1号数据型。
     * 2，修改--表： wx_order_outgo  wx_order表的修改是外部代码修改的
     *
     * 0号数据型--条件：
     * 1，财务审核过的不能修改。
     * 2，尾部完成的订单不修改。
     * 修改方案：
     * 1，修改表： wx_order_outgo   wx_order_outgo_order
     *
     * 原业务流程： 工序再细化。
     * 1，1号数据型，不流入 财务数据。
     */
    public function edit_factoryId($orderId, $factoryId, $group_id = 0, $type = 1)
    {
        //1, 判断是那个： 0 1号数据型 。并标识 增 删 改
        $data_info = $this->get_data_status($orderId, $factoryId, $group_id, $type);
        //2,根据不同数据型 修改工厂id
        switch ($data_info['data_status']) {
            case 1:
                switch ($data_info['action']) {
                    case 'add':
                        $res = db('order_outgo')->insert([
                            'order_id' => $orderId,
                            'group_id' => $group_id,
                            'hope_shipment_time' => 0,
                            'cut_packages' => 0,
                            'cut_packages_remark' => '',
                            'status' => 300,
                            'data_status' => 1,
                            'admin_id' => ADMIN_ID,
                            'create_time' => time(),
                            'update_time' => time(),
                        ]);
                        if ($res != 1) {
                            return $this->return_logic(12, '设置失败');
                        }
                        return $this->return_logic(1, '');
                        break;
                    case 'edit'://修改--表： wx_order_outgo
                        $temp = db('order_outgo')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'group_id' => $group_id,
                            'data_status' => 1,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != 1) {
                            return $this->return_logic(13, '设置失败', $temp);
                        }
                        return $this->return_logic(1, '');
                        break;
                    case 'del':
                        if ($data_info['flag'] == false) {
                            return $this->return_logic(14, '设置失败');
                        }
                        $temp = db('order_outgo')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'group_id' => 0,
                            'status' => 0,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != 1) {
                            return $this->return_logic(13, '设置失败', $temp);
                        }
                        return $this->return_logic(1, '');
                        break;
                }
                break;
            case 0:
                switch ($data_info['action']) {
                    case 'add':
                        $res = db('order_outgo')->insert([
                            'order_id' => $orderId,
                            'group_id' => $group_id,
                            'hope_shipment_time' => 0,
                            'cut_packages' => 0,
                            'cut_packages_remark' => '',
                            'status' => 0,
                            'data_status' => 0,
                            'admin_id' => ADMIN_ID,
                            'create_time' => time(),
                            'update_time' => time(),
                        ]);
                        if ($res != 1) {
                            return $this->return_logic(12, '设置失败');
                        }
                        //由$group_id作用于 order_outgo的status字段设置
                        $temp = $this->_edit_factoryId_group_status_100($orderId, $group_id);
                        return $this->return_logic(1, '');
                        break;
                    case 'edit'://修改--表： wx_order_outgo wx_order_outgo_cpl   wx_order_outgo_order
                        $temp = db('order_outgo')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'group_id' => $group_id,
                            'data_status' => 0,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != 1) {
                            return $this->return_logic(13, '设置失败', $temp);
                        }
                        if ($group_id == 0) {
                            $temp = db('order_outgo_cpl')->where([
                                ['order_id', '=', $orderId],
                            ])->delete();
                        }
                        $count = db('order_outgo_order')->where([
                            ['order_id', '=', $orderId],
                        ])->count();
                        $temp = db('order_outgo_order')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'factory_id' => $factoryId,
                            'factory_child_id' => $group_id,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != $count) {
                            return $this->return_logic(14, '设置失败', $temp);
                        }
                        //车间的倍率修改
                        $temp = db('order_outgo_order')->where([
                            ['order_id', '=', $orderId],
                            ['type', '=', 'waitDeliver_sendConfirm'],
                        ])->update([
                            'group_unit_price' => floatval($data_info['data']['unit_workshop']),
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        //由$group_id作用于 order_outgo的status字段设置
                        $temp = $this->_edit_factoryId_group_status_100($orderId, $group_id);
                        return $this->return_logic(1, '');
                        break;
                    case 'del'://修改--表： wx_order_outgo wx_order_outgo_cpl   wx_order_outgo_order
                        $count = db('order_outgo')->where([
                            ['order_id', '=', $orderId],
                        ])->count();
                        $temp = db('order_outgo')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'group_id' => 0,
                            'data_status' => 0,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != $count) {
                            return $this->return_logic(13, '设置失败', $temp);
                        }
                        $temp = db('order_outgo_cpl')->where([
                            ['order_id', '=', $orderId],
                        ])->delete();
                        $count = db('order_outgo_order')->where([
                            ['order_id', '=', $orderId],
                        ])->count();
                        $temp = db('order_outgo_order')->where([
                            ['order_id', '=', $orderId],
                        ])->update([
                            'factory_id' => 0,
                            'factory_child_id' => 0,
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                        ]);
                        if ($temp != $count) {
                            return $this->return_logic(13, '设置失败', $temp);
                        }
                        //由$group_id作用于 order_outgo的status字段设置
                        $temp = $this->_edit_factoryId_group_status_100($orderId, $group_id);
                        return $this->return_logic(1, '');
                        break;
                }
                break;
        }
        return $this->return_logic(100, '设置失败');
    }

    //由子工厂==》引发的order_outgo表的status状态改变
    private function _edit_factoryId_group_status_100($orderId, $group_id)
    {
        $temp_info = db('order_outgo')->where([
            ['order_id', '=', $orderId],
        ])->find();
        $group_info = db('group g')
            ->field('g.id,g.unit_set_flag')
            ->where([
                ['g.id', '=', $group_id],
            ])->find();
        $status = ($group_id > 0
            && isset($group_info['unit_set_flag'])
            && $group_info['unit_set_flag'] == 2) ? 100 : 0;
        $status_res = $temp_info['status'] > $status ? $temp_info['status'] : $status;
        if ($status_res == 100) {
            if (isset($group_info['unit_set_flag']) && $group_info['unit_set_flag'] == 0
                && $temp_info['u_scale'] <= 0 && $temp_info['u_price_manual'] <= 0
            ) {
                $status_res = 0;
            }
        }
        $temp = db('order_outgo')->where([
            ['order_id', '=', $orderId],
        ])->update([
            'status' => $status_res,
        ]);
        return $temp;
    }

    /**
     * 判断是那个： 0 1号数据型 。并标识 增 删 改
     * @param $orderId
     * @param $factoryId
     */
    public function get_data_status($orderId, $factoryId, $group_id, $type)
    {
        $temp = db('order o')
            ->field('o.id,o.chejian_status,o.tail_status,odr.status as odr_status
            ,outgo.status as outgo_status,outgo.data_status as outgo_data_status
             ,g.unit_cutting,g.unit_workshop,g.unit_tail,g.unti_manual,g.unit_time_price,g.unit_set_flag
            ')
            ->join('order_outgo outgo ', 'o.id=outgo.order_id', 'left')
            ->join('order_outgo_order odr ', 'o.id=odr.order_id', 'left')
            ->join('group g', "g.id=outgo.group_id", 'left')
            ->where([
                ['o.id', '=', $orderId],
            ])->find();
        if ($temp['odr_status'] >= 1120) {//财务有审核就不能修改了。
            return ['data_status' => 10];
        }
        $data_status = 0;
        switch ($temp['outgo_data_status']) {
            case 0:
                break;
            default:
                if ($temp['chejian_status'] == 1 && $temp['tail_status'] == 0 && !isset($temp['outgo_data_status'])) {
                    $data_status = 1;
                }
                if ($temp['outgo_data_status'] == 1) {
                    $data_status = 1;
                }
                break;
        }
        switch ($data_status) {
            case 1:
                if (($temp['tail_status'] > 0)) {
                    return ['data_status' => 10];
                }
                if ($temp['outgo_data_status'] == 1 && $temp['outgo_status'] > 300 && $type == 0) {//不删除了
                    return ['data_status' => $data_status, 'action' => 'del', 'flag' => false,];
                }
                if ($temp['outgo_data_status'] == 1 && $type == 0) {
                    return ['data_status' => $data_status, 'action' => 'del', 'flag' => true,];
                }
                if ($temp['outgo_data_status'] == 1) {
                    return ['data_status' => $data_status, 'action' => 'edit'];
                }
                if (!isset($temp['outgo_data_status'])) {
                    return ['data_status' => $data_status, 'action' => 'add'];
                }
                break;
            case 0:
                if (($temp['tail_status'] > 0)) {
                    return ['data_status' => 10];
                }
                if ($type == 1 && isset($temp['outgo_data_status'])) {
                    return ['data_status' => $data_status, 'action' => 'edit', 'data' => ['unit_workshop' => $temp['unit_workshop']]];
                }
                if ($type == 0) {
                    return ['data_status' => $data_status, 'action' => 'del'];
                }
                if (!isset($temp['outgo_data_status'])) {
                    return ['data_status' => $data_status, 'action' => 'add'];
                }
                break;
        }
        return ['data_status' => 10];
    }

    public function return_logic($code = 1, $msg = '', $data = [], $count = 0)
    {
        if (empty($msg)) {
            $msg = $code == 1 ? '操作成功' : '操作失败';
        }
        return ['code' => $code, 'msg' => $msg, 'data' => $data, 'count' => $count];
    }

    /**
     * 委外对帐的审核
     * @param $param
     * @return array
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/2
     */
    public function outCheckOrder_check($param)
    {
        $status = $param['status'];
        $ids = $param['ids'];
        $type = $param['type'];
        $stall_feed_id = $param['stall_feed_id'];
        if (!defined('ADMIN_ID')) {
            define('ADMIN_ID', 0);
        }
        //2,order_outgo_order表修改
        switch ($status) {
            case 1120://1，如入仓数为0则 不能审核。2，如表为0，设置sum_store_count的值 3，计算加工费总金额
                Db::startTrans();
                try {
                    $info = $this->_outCheckOrder_check_1120($ids, $param);
                    if ($info['code'] > 0) {
                        Db::rollback();
                        return $this->return_logic(10, $info['msg'], $info);
                    }
                    $temp = db('order_outgo_order')->where([
                        ['id', 'in', $ids],
                        ['status', 'in', [1101, 1102]],
                    ])->update([
                        'status' => 1120,
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'auto_admin_id' => $param['auto_admin_id'],
                        'admin_id_1120' => ADMIN_ID,
                        'time_update_1120' => time(),
                    ]);
                    if ($temp == count($ids)) {
                        Db::commit();
                        return $this->return_logic(1, '审核成功', $temp);
                    }
                    Db::rollback();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->return_logic(100, '失败', [$e->getCode(),
                        $e->getMessage()],);
                }
                break;
            case 1101:
                $temp = db('order_outgo_order')->where([
                    ['id', 'in', $ids],
                    ['status', '=', 1120],
                ])->update([
                    'status' => 1101,
                    'update_time' => time(),
                    'admin_id' => ADMIN_ID,
                    'auto_admin_id' => $param['auto_admin_id'],
                    'admin_id_1101' => ADMIN_ID,
                    'time_update_1101' => time(),
                ]);
                if ($temp == count($ids)) {
                    return $this->return_logic(1, '撤消成功', $temp);
                }
                break;
            case 1102://驳回
                Db::startTrans();
                try {
                    switch ($type) {
                        case 'all'://$ids就表示为 wx_order_outgo_order_group表的id
                            $temp_ids = db('order_outgo_order ooor')
                                ->field('ooor.id,ooor.factory_id,ooor.factory_child_id
                        ')
                                ->join('order_outgo_order_group ogp', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                                ->where([
                                    ['ogp.id', 'in', $ids],
                                    ['ooor.status', '=', 1140],
                                ])
                                ->select();
                            $ids = [];
                            foreach ($temp_ids as $k => $v) {
                                $ids[] = $v['id'];
                            }
                            break;
                    }
                    $order_outgo_order_group_id_array = db('order_outgo_order')
                        ->field('order_outgo_order_group_id')
                        ->where([
                            ['id', 'in', $ids],
                            ['status', '=', 1140],
                        ])->group('order_outgo_order_group_id')->select();
                    //3,业务=》order_outgo_order 表修改
                    $temp = db('order_outgo_order')->where([
                        ['id', 'in', $ids],
                        ['status', '=', 1140],
                    ])->update([
                        'status' => 1102,
                        'order_outgo_order_group_id' => 0,
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'auto_admin_id' => $param['auto_admin_id'],
                        'admin_id_1102' => ADMIN_ID,
                        'time_update_1102' => time(),
                    ]);
                    if ($temp != count($ids)) {
                        Db::rollback();
                        return $this->return_logic(10, '驳回失败', $ids);
                    }
                    //3.2,业务=》wx_order_outgo_order_group表修改--可能 1300作废-只对这个组集表
                    foreach ($order_outgo_order_group_id_array as $k => $v) {
                        $temp_count = db('order_outgo_order')
                            ->where([
                                ['order_outgo_order_group_id', '=', $v['order_outgo_order_group_id']],
                                ['status', '=', 1140],
                            ])->count();
                        if ($temp_count == 0) {
                            $temp = db('order_outgo_order_group')->where([
                                ['id', '=', $v['order_outgo_order_group_id']],
                            ])->update([
                                'status' => 1300,
                                'update_time' => time(),
                                'admin_id' => ADMIN_ID,
                            ]);
                            if ($temp != 1) {
                                Db::rollback();
                                return $this->return_logic(11, '驳回失败', [$temp_count, $temp]);
                            }
                        }
                    }
                    Db::commit();
                    return $this->return_logic(1, '驳回成功');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->return_logic(100, '失败');
                }
                break;
            case 1130://返已审核
                Db::startTrans();
                try {
                    //查询表
                    $info = db('order_outgo_order ooor')
                        ->field('ooor.id,ooor.factory_id,ooor.factory_child_id,ooor.order_outgo_order_group_id
                        ')
                        ->where([
                            ['ooor.id', 'in', $ids],
                        ])->find();
                    $temp = db('order_outgo_order')->where([
                        ['id', 'in', $ids],
                        ['status', '=', 1130],
                    ])->update([
                        'status' => 1120,
                        'order_outgo_order_group_id' => 0,
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'auto_admin_id' => $param['auto_admin_id'],
                        'admin_id_1120' => ADMIN_ID,
                        'time_update_1120' => time(),
                    ]);
                    if ($temp != count($ids)) {
                        Db::rollback();
                        return $this->return_logic(10, '失败', $temp);
                    }
                    $count = db('order_outgo_order ooor')
                        ->field('ooor.id,ooor.factory_id,ooor.factory_child_id
                        ')
                        ->where([
                            ['ooor.factory_id', '=', $info['factory_id']],
                            ['ooor.factory_child_id', '=', $info['factory_child_id']],
                            ['ooor.order_outgo_order_group_id', '=', $info['order_outgo_order_group_id']],
                            ['ooor.status', '=', 1130],
                        ])->count();
                    if ($count == 0) {
                        $temp = db('order_outgo_order_group')->where([
                            ['id', '=', $stall_feed_id],
                        ])->delete();
                        if ($temp != 1) {
                            Db::rollback();
                            return $this->return_logic(11, '失败', $temp);
                        }
                    }
                    Db::commit();
                    return $this->return_logic(1, '成功', $temp);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->return_logic(100, '失败');
                }
                break;
        }
        return $this->return_logic(10, '失败');
    }

    //1，如入仓数为0则 不能审核。2，如表为0，设置sum_store_count的值 3，计算加工费总金额  加工费总金额=   委外单价(MES加工费*委外倍率) *MES入仓总数 - (捆条金额 + 返工金额+其它扣款)
    private function _outCheckOrder_check_1120($ids, $param)
    {
        $list = db('order_outgo_order ooor')
            ->field('ooor.* , oext.cost_little as order_cost_little')
            ->join('order_ext oext', "ooor.order_id=oext.order_id", 'left')
            ->where([
                ['ooor.id', 'in', $ids],
                ['ooor.status', 'in', [1101, 1102]],
            ])->select();
        foreach ($list as $k => $v) {
            $sum_store_count = intval($v['sum_store_count']);
            if (intval($v['sum_store_count']) > 0) {
            } else {
                $osList = (new OrderSizeService())->getListByOrderId($v['order_id']);
                $sum_store_count = array_sum(array_column($osList, 'delivery_count'));
                $list[$k]['sum_store_count'] = $v['sum_store_count'] = $sum_store_count;
                if ($sum_store_count <= 0) {
                    return ['code' => 10, 'msg' => 'MES入仓总数为0，不能审核'];
                } else {
                    $temp = db('order_outgo_order')->where([
                        ['id', '=', $v['id']],
                    ])->update([
                        'sum_store_count' => $sum_store_count,
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'auto_admin_id' => $param['auto_admin_id'],
                    ]);
                    if ($temp != 1) {
                        return ['code' => 11, 'msg' => '审核失败'];
                    }
                }
            }
            $this->_deal_with_index_m0($list[$k]);
//            //改为：加工费总金额=   委外单价(MES加工费的小计*委外倍率) *MES入仓总数 不用 - (捆条金额 + 返工金额+其它扣款)
//            $cost_little = $v['cost_little'];
//            $v['cost_little'] <= 0 && floatval($v['order_cost_little']) > 0 && $cost_little = $v['order_cost_little'];
            if ($list[$k]['cost_little'] <= 0) {
                return ['code' => 13, 'msg' => '审核失败,小计为0', 'data' => []];
            }
            if ($list[$k]['price_all'] <= 0) {
                return ['code' => 14, 'msg' => '审核失败', 'data' => []];
            }
            $temp = db('order_outgo_order')->where([
                ['id', '=', $v['id']],
            ])->update([
                'price_all' => $list[$k]['price_all'],
                'cost_little' => $list[$k]['cost_little'],
                'sum_stock_in' => $list[$k]['sum_stock_in'],
                'update_time' => time(),
                'admin_id' => ADMIN_ID,
                'auto_admin_id' => $param['auto_admin_id'],
            ]);
            if ($temp != 1) {
                return ['code' => 12, 'msg' => '审核失败'];
            }
        }
        return ['code' => 0, 'msg' => ''];
    }

    //关系到加工费总金额，的参数处理
    public function _deal_with_index_m0(&$v)
    {
        $cost_little = $v['cost_little'];
        $v['cost_little'] <= 0 && floatval($v['order_cost_little']) > 0 && $cost_little = $v['order_cost_little'];
        $v['cost_little'] = $cost_little;//加工费的小计
        //米莫入库数
        if ($v['sum_stock_in'] <= 0) {
            $temp = db('sku_stock_log')->field('sum(available_count) as sum_available_count')->where([
                ['order_id', '=', $v['order_id']],
                ['action_type', '=', 1],
            ])->find();
            $v['sum_stock_in'] = intval($temp['sum_available_count']);
        }
        //实际结算总数
        $v['real_pay_count'] = $v['sum_store_count'] + $v['sum_stock_in'];
        switch ($v['unit_set_flag']) {
            case 2://原规则
                $v['mes_cost_res'] = $cost_little; //MES加工费（元）---旧取 $cost_little 新取 cost_jiagong_sumCostForSale
                $v['unit_num'] = $v['group_unit_price'];//委外倍率
                $v['group_out_type_txt'] = $this->_get_group_out_type_txt($v['group_out_type']);
                $v['order_price_res'] = sprintf("%.2f", $cost_little * $v['group_unit_price']);
                $v['order_price_res_changkuan'] = sprintf("%.2f", 0);
                //加工费总金额
                $v['price_all'] = sprintf("%.2f", $v['order_price_res'] * $v['real_pay_count']);
                break;
            case 0:
                $v['mes_cost_res'] = $v['cost_jiagong_sumCostForSale'];
                $v['unit_num'] = $v['u_scale'];//委外倍率
                $v['group_out_type_txt'] = $this->_get_group_out_type_txt($v['u_out_type']);
                $v['order_price_res'] = sprintf("%.2f", $v['cost_jiagong_littleSumCost'] * $v['u_scale'] + $v['u_price_manual'] + $v['dress_changkuan_unitPrice'] * $v['u_scale_changkuan']);
                $v['order_price_res_changkuan'] = sprintf("%.2f", $v['dress_changkuan_unitPrice'] * $v['u_scale_changkuan']);
                //加工费总金额
                $v['price_all'] = sprintf("%.2f", $v['order_price_res'] * $v['real_pay_count']);
                if (env('env_site') == 'riwei') {
                    $v['price_all'] = sprintf("%.2f", $v['order_price_res'] * $v['sum_jiaohuo_tail_count']);
                }
                break;
        }
        return true;
    }

    public function _get_group_out_type_txt($type)
    {
        $temp = explode(',', $type);
        $txt = '';
        foreach ($temp as $k => $v) {
            switch ($v) {
                case 1:
                    $txt .= '裁,';
                    break;
                case 2:
                    $txt .= '车,';
                    break;
                case 3:
                    $txt .= '尾,';
                    break;
                case 4:
                    $txt .= '专机,';
                    break;
            }
        }
        $txt = substr($txt, 0, -1);
        return $txt;
    }

    /**
     * 回货记录
     * order_outgo_batch表的回货记录
     * type 数据类型，return回货批次，owe欠数批次  回货类型：sewing车缝中的回货 finishReturn 已退货的回货(与num分批数因无限循环) outgoTail 外协尾部的回货(与num分批数因无限循环)
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/26
     */
    public function order_outgo_batch_return($type = 'sewing', $info, $return_num, $return_owe, $return_material_flag)
    {
        switch ($type) {
            case 'sewing':
            case 'finishReturn':
            case 'outgoTail':
                $num = 1;
                $temp = db('order_outgo_batch')->where([
                    ['order_id', '=', $info['order_id']],
                    ['type', '=', $type],
                ])->order('num desc')->limit(1)->find();
                isset($temp['num']) && $num = $temp['num'] + 1;
                $return_list = [];
                $return_list[] = [
                    'order_id' => $info['order_id'],
                    'client_ordernum' => $info['client_ordernum'],
                    'num' => $num,
                    'type' => $type,
                    'size_mid' => 0,
                    'size_name' => '',
                    'count' => 0,
                    'return_num' => $return_num,
                    'return_owe' => $return_owe,
                    'return_material_flag' => $return_material_flag,
                    'admin_id' => ADMIN_ID,
                    'update_time' => time(),
                    'create_time' => time(),
                ];
                return db('order_outgo_batch')->insertAll($return_list);
                break;
        }
        return true;
    }

    /**
     * 委外前置 特别权限，如黑客性修改
     * @param $param
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/5
     */
    public function unitSet_super($param)
    {
        $info = db('order_outgo oot')
            ->field("oot.id,oot.order_id,oot.status as status_oot 
            ,otdr.status as status_otdr,otdr.unit_set_flag")
            ->join('order_outgo_order otdr', 'oot.order_id=otdr.order_id', 'left')
            ->where([
                ['oot.order_id', '=', $param['order_id']],
            ])->find();
        if ($info['status_otdr'] >= 1120) {
            return ['code' => 1120, 'msg' => '此单在委外对账中已审核'];
        }
        switch ($info['unit_set_flag']) {
            case 2://原规则
                return ['code' => 12, 'msg' => '此单不能修改，因不是委外前置'];
                break;
            case 0:
                if ($info['unit_set_flag'] == 0) {
                    if ($param['u_out_type'] == '') {
                        return ['code' => 10, 'msg' => '设置失败'];
                    }
                    if ($param['u_scale'] <= 0 && $param['u_price_manual'] <= 0) {
                        return ['code' => 20, 'msg' => '设置失败'];
                    }
                }
                //2,业务->修改表 wx_order_outgo
                $temp = db('order_outgo oot')
                    ->where([
                        ['oot.order_id', '=', $param['order_id']],
                    ])->update([
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'u_out_type' => $param['u_out_type'],
                        'u_scale' => $param['u_scale'],
                        'u_price_manual' => $param['u_price_manual'],
                        'u_scale_changkuan' => $param['u_scale_changkuan'],
                    ]);
                if ($temp != 1) {
                    return ['code' => 11, 'msg' => '设置失败'];
                }
                //2,业务->修改表 wx_order_outgo
                $info2 = db('order_outgo_order')->where([
                    ['order_id', '=', $info['order_id']],
                    ['type', '=', 'waitDeliver_sendConfirm'],
                ])->find();
                if (isset($info2['id'])) {
                    //2,计算处理
                    //3,添加或修改 wx_order_outgo_order表
                    $temp = db('order_outgo_order')->where([
                        'order_id' => $param['order_id'],
                        'type' => 'waitDeliver_sendConfirm',
                    ])->update([
                        'u_out_type' => $param['u_out_type'],
                        'u_scale' => $param['u_scale'],
                        'u_price_manual' => $param['u_price_manual'],
                        'u_scale_changkuan' => $param['u_scale_changkuan'],
//                        'unit_set_flag' => $info['unit_set_flag'],
                        'admin_id' => ADMIN_ID,
                        'update_time' => time(),
                    ]);
                    if ($temp != 1) {
                        return ['code' => 12, 'msg' => '设置失败'];
                    }
                }
                break;
        }
        return ['code' => 0, 'msg' => '设置成功'];
    }
}